package com.iot.modbus.reader.impl;

import com.iot.modbus.manager.ReaderSessionManager;
import com.iot.modbus.reader.Reader;
import com.iot.modbus.reader.ReaderSession;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ModbusRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;

import java.nio.ByteOrder;

/**
 * 简单ReaderSession
 */
public class SimpleReaderSession implements ReaderSession {

    private ModbusMaster master;

    public SimpleReaderSession(ModbusMaster master) {
        this.master = master;
    }

    @Override
    public boolean readBoolean16(int startOffset, ByteOrder byteOrder, int bit) {
        return (readInt16(startOffset, byteOrder) >>> bit & 1) != 0;
    }

    @Override
    public short[] read(int startOffset, int numberOfRegisters) {
        ReadInputRegistersRequest request = null; // 起始地址为 0，读取 10 个寄存器
        try {
            ModbusRequest readRequest = ReaderSessionManager.createReadRequest(1, 3, startOffset, numberOfRegisters);
            ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(readRequest);
            return response.getShortData();
        } catch (ModbusTransportException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public short readInt16(int startOffset, ByteOrder byteOrder) {
        return read(startOffset,2)[0];
    }

    @Override
    public int readUInt16(int startOffset, ByteOrder byteOrder) {
        return Reader.convertRegistersToUInt16(read(startOffset,2),0,byteOrder);
    }

    @Override
    public int readInt32(int startOffset, ByteOrder byteOrder) {
        return  Reader.convertRegistersToInt32(read(startOffset,4),0,byteOrder);
    }

    @Override
    public long readUInt32(int startOffset, ByteOrder byteOrder) {
        return  Reader.convertRegistersToUInt32(read(startOffset,4),0,byteOrder);
    }

    @Override
    public long readInt64(int startOffset, ByteOrder byteOrder) {
        return  Reader.convertRegistersToInt64(read(startOffset,8),0,byteOrder);
    }

    @Override
    public float readFloat32(int startOffset, ByteOrder byteOrder) {
        return  Reader.convertRegistersToFloat32(read(startOffset,4),0,byteOrder);
    }

    @Override
    public double readFloat64(int startOffset, ByteOrder byteOrder) {
        return Reader.convertRegistersToFloat64(read(startOffset,8),0,byteOrder);
    }


}
